package io.xccit.system.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.xccit.common.enums.ResultCodeEnum;
import io.xccit.common.exception.AuthCustomException;
import io.xccit.common.result.AjaxResult;
import io.xccit.common.utils.JwtHelper;
import io.xccit.common.utils.MD5;
import io.xccit.log.annotation.Log;
import io.xccit.log.enums.BusinessType;
import io.xccit.model.system.SysUser;
import io.xccit.model.vo.LoginVo;
import io.xccit.system.service.ISysUserService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author CH_ywx
 * @date 2023-06-24
 * @description 管理员接口
 */

@Api(tags = "管理员接口")
@RestController
@RequestMapping("/api/system/admin")
@CrossOrigin
public class AdminController {

    @Resource
    private ISysUserService sysUserService;

    @Log(title = "用户登录")
    @PostMapping("/login")
    @ApiOperation("管理员登录")
    public AjaxResult<Map<String, Object>> login(@RequestBody LoginVo loginVo) {
        Map<String, Object> result = new HashMap<>();
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        SysUser sysUser = sysUserService.login(username);
        if (sysUser == null) {
            throw new AuthCustomException(ResultCodeEnum.ACCOUNT_ERROR);
        }
        if (sysUser.getStatus() == 0){
            throw new AuthCustomException(ResultCodeEnum.ACCOUNT_STOP);
        }
        if (!sysUser.getPassword().equals(MD5.encrypt(password))) {
            throw new AuthCustomException(ResultCodeEnum.PASSWORD_ERROR);
        }
        String token = JwtHelper.createToken(sysUser.getId(), sysUser.getUsername());
        result.put("token", token);
        return AjaxResult.ok(result);
    }

    @Log(title = "用户信息获取")
    @GetMapping("/info")
    @ApiOperation("获取管理员信息")
    public AjaxResult<Map<String, Object>> info(HttpServletRequest request) {
        String token = request.getHeader("token");
        String username = JwtHelper.getUsername(token);
        Map<String, Object> result = sysUserService.getUserInfo(username);
        return AjaxResult.ok(result);
    }

    @Log(title = "用户退出登录")
    @PostMapping("/logout")
    @ApiOperation("管理员退出登录")
    public AjaxResult<Boolean> logout() {
        return AjaxResult.ok(true);
    }
}
